<?php

namespace app\common\func;

use app\common\model\Balance;
use app\common\model\BalanceTotal;
use app\common\model\CompanyStocks;
use app\common\model\CompanyStocksLogs;
use app\common\model\Equip;
use app\common\model\EquipRate;
use app\common\model\MoneyLogs;
use app\common\model\Product;
use app\common\model\TranCalculate;
use app\common\model\TranProfit;
use app\common\model\User;
use fast\Random;
use fast\Tree;
use think\Db;

class Tools
{

    /**
     * 微信回调数据解密
     * @param $data | 加密数据
     * @param $key  | 支付密钥
     * @return false|string
     */
    public static function wxNotifyDecrypt($data,$key){
        $key = md5($key);
        $str = base64_decode($data);
        return openssl_decrypt($str, 'aes-256-ecb', $key, OPENSSL_RAW_DATA);
    }

    public static function getPemContent($fileName){
        $path = ROOT_PATH."public/file/pem/" . $fileName;
        $pemContent = file_get_contents($path);
        $pemContent = preg_replace('/-----BEGIN(.*)-----/', '', $pemContent);
        $pemContent = preg_replace('/-----END(.*)-----/', '', $pemContent);
        $pemContent = preg_replace('/\s+/', '', $pemContent);
        return $pemContent;
    }

    public static function getTranType($product,$type){
        switch ($product){
            case "jl":
                if(in_array($type,['02','12'])){
                    return 1;
                }elseif (in_array($type,['01','11'])){
                    return 3;
                }else{
                    return 2;
                }
                break;
            case "ys":
                if($type == "06"){
                    return 1;
                }elseif ($type == "05"){
                    return 3;
                }else{
                    return 2;
                }
                break;
            case "sft":
                if(in_array($type,['CC','SCC'])){
                    return 1;
                }elseif (in_array($type,['DC'])){
                    return 3;
                }else{
                    return 2;
                }
                break;
        }
    }

    /**
     * @param $productId || 产品ID
     * @param $userId || 接收设备用户ID
     * @param $updateTime || 调整设备用户时间
     * @param $endTime || 设备活动结束时间
     * @return false|int
     * @throws \think\exception\DbException
     */
    public static function getEquipEndTime($productId,$userId,$updateTime,$endTime){
        $user = Lib::getUserInfo($userId);
        $standards = Libs::getStandardsDay($productId,Constant::$levelAlia[$user->buy_level]);
        $end = strtotime("+".$standards->day_limit." day",$updateTime);

        return $end >= $endTime ? $endTime : $end;
    }

    //根据用户查询对应的代理、机构、核心
    public static function getUserLevel($userId){
        $arr = [];
        $level = self::getUserChild($userId,5);
        if(count($level) > 0){
            $arr['AG'] = $level[0]['id'];
            foreach ($level as $key => $val){
                if($val['buy_level'] == "JG" && !isset($arr['JG'])){
                    $arr['JG'] = $val['id'];
                }else{
                    if($val['buy_level'] == "HX" && !isset($arr['HX'])){
                        if(!isset($arr['JG'])){
                            $arr['JG'] = $val['id'];
                            $arr['HX'] = $val['id'];
                        }else{
                            $arr['HX'] = $val['id'];
                        }
                    }else{
                        if (isset($arr['HX'])){
                            break;
                        }else{
                            continue;
                        }
                    }
                }
            }
        }

        return $arr;
    }

    /**
     * -----------------------------------------通过交易额确定分润计算费率---------------------------------------------------
     */

    //保存用户产品当月交易额
    public static function saveUserTranMonth($mainType,$mainId,$productId,$tranAmount,$tranTime){
        $month = date("Y-m",$tranTime);
        $tranCalculate = TranCalculate::where(["main_type" => $mainType,"main_id" => $mainId,"product_id" => $productId,"month" => $month])->find();
        if(!$tranCalculate){
            $tranCalculate = new TranCalculate();
            $tranCalculate->main_type = $mainType;
            $tranCalculate->main_id = $mainId;
            $tranCalculate->product_id = $productId;
            $tranCalculate->month = $month;
            $tranCalculate->total_tran = 0;
        }
        $tranCalculate->total_tran += $tranAmount;
        $rate = self::getRateByTran($tranCalculate->total_tran);
        if($rate && $rate->id != $tranCalculate->tran_profit_id){
            $tranCalculate->tran_profit_id = $rate->id;
            $tranCalculate->tran_profit_rate = $rate->rate;
        }
        $tranCalculate->save();

    }

    //通过交易额查询费率
    public static function getRateByTran($tranAmount){
        return TranProfit::where("start_money","<",$tranAmount/10000)->order("start_money desc")->find();
    }

    //查询用户产品费率
    public static function getUserRateByTran($mainType,$mainId,$productId){
        $month = mktime(0,0,0,date('m') -1,1,date('Y'));
        $month = date("Y-m",$month);
        $rate = TranCalculate::where(["main_type" => $mainType,"main_id" => $mainId,"product_id" => $productId,"month" => $month])->find();
        return $rate ? $rate->tran_profit_rate : 0;
    }

    /**
     * -----------------------------------------通过交易额确定分润计算费率---------------------------------------------------
     */


    public static function countSize($size, $sep = '')
    {
        $unit = null;
        $units = array('B', 'KB', 'MB', 'GB', 'TB');

        for ($i = 0, $c = count($units); $i < $c; $i++) {
            if ($size > 1024) {
                $size = $size / 1024;
            } else {
                $unit = $units[$i];
                break;
            }
        }

        return round($size, 2) . $sep . $unit;
    }

    //查询满足返现、达标条件的订单数据
    public static function getSatisfyOrder($sn, $money, $tableName,$startTime = 0)
    {
        $sql = "SELECT * FROM (SELECT a.*,IF(@sum + a.transaction_amount >= " . $money . " AND @isOk = 'no', @isOk := 'yes', @sum := @sum + a.transaction_amount) result,@sum,@isOk FROM fd_" . $tableName . " a,(SELECT @sum := 0,@isOk := 'no') AS it where handle_state != 3 and a.sn = '" . $sn . "' AND a.trading_time > ".$startTime." ORDER BY a.trading_time asc) temp WHERE temp.result = 'yes'";
        return Db::query($sql);
    }

    //处理人名，只显示名字首字
    public static function handleName($name)
    {
        return mb_substr($name, 0, 1) . str_repeat("*", mb_strlen($name) - 1);
    }

    public static function getCompanyChildUser($companyId)
    {
        return User::where(["ptype" => 1, "pid" => $companyId])->field("id,pid,nickname as name,ptype,mobile")->select();
    }

    /**
     * @param $mainId
     * @param int $type || 0=默认，1=所有下级(树形)，2=直属下级（二维数组），3=所有下级（二维数组），4=所有下级ID（数组）
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getCompanyChild($mainId, $type = 0)
    {
        $list = Db::name("company")->where(["status" => 1])->field("id,pid,name,contact_phone as mobile")->select();
        $query = Tree::instance()->init($list, 'pid');
        switch ($type) {
            case 1:
                $data = $query->getTreeArray($mainId);
                break;
            case 2:
                $data = $query->getChild($mainId);
                break;
            case 3:
                $data = $query->getChildren($mainId);
                break;
            case 4:
                $data = $query->getChildrenIds($mainId);
                break;
            default:
                $data = [];
        }
        return $data;
    }

    /**
     * @param $mainId
     * @param int $type || 0=默认，1=所有下级(树形)，2=直属下级（二维数组），3=所有下级（二维数组），4=所有下级ID（数组），5=父级（包括自己）
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getUserChild($mainId, $type = 0)
    {
        $list  = Db::name("user")->field("id,pid,nickname as name,ptype,mobile,buy_level")->order("id desc")->select();
        $query = Tree::instance()->init($list, 'pid');
        switch ($type) {
            case 1:
                $data = $query->getTreeArray($mainId);
                break;
            case 2:
                $data = $query->getChild($mainId);
                break;
            case 3:
                $data = $query->getChildren($mainId);
                break;
            case 4:
                $data = $query->getChildrenIds($mainId);
                break;
            case 5:
                $data = $query->getParents($mainId,true);
                break;
            default:
                $data = [];
        }
        return $data;
    }

    public static function getParentInfo($mainType, $mainId)
    {
        $arr = [];
        switch ($mainType) {
            case 1:
                $company = Lib::getCompany($mainId);
                $arr = ["ptype" => 1, "pid" => $company->pid];
                break;
            case 2:
                $user = Lib::getUserInfo($mainId);
                $arr = ["ptype" => $user->ptype, "pid" => $user->pid];
                break;
        }

        $result = [];
        switch ($arr['ptype']) {
            case 1:
                $company = Lib::getCompany($arr['pid']);
                $result = ["type" => 1, "obj" => $company];
                break;
            case 2:
                $user = Lib::getUserInfo($arr['pid']);
                $result = ["type" => 2, "obj" => $user];
                break;
        }

        return $result;
    }

    public static function updateEquip($productId,$snList, $mainType, $mainId,$completeTime = 0)
    {
        if (count($snList) > 0) {
            foreach ($snList as $key => $val) {
                $equip = Lib::getEquip($val['sn']);
                if(!$equip){
                    $equip = new Equip();
                    $equip->sn = $val['sn'];
                    $equip->product_id = $productId;

                    $equipRate = new EquipRate();
                    $equipRate->proid = $productId;
                    $equipRate->sn = $val['sn'];
                    $equipRate->state = "D";
                    $equipRate->rate = "0.60";
                    $equipRate->save();
                }
                $equip->main_type = $mainType;
                $equip->main_id = $mainId;

                $equip->save();
            }
        }
    }

    public static function updateEquipInfo($snList, $mainType, $mainId)
    {
        if (count($snList) > 0) {
            foreach ($snList as $key => $val) {
                $equip = Lib::getEquip($val['sn']);
                $equip->main_type = $mainType;
                $equip->main_id = $mainId;
                $equip->sn = $val['sn'];
                $equip->save();
            }
        }
    }

    /**
     * @param $mainType
     * @param $mainId
     * @param $balanceId
     * @param $moneyType
     * @param $money
     * @param $sn | 设备号
     * @param $productId | 产品
     * @param string $memo
     * @param array $extend
     */
    public static function saveMoney($mainType, $mainId, $balanceId, $moneyType, $money, $sn, $productId, $memo = "", $extend = [])
    {
        $log = new MoneyLogs();
        $log->main_type = $mainType;
        $log->main_id = $mainId;
        $log->balance_type_id = $balanceId;
        $log->money_type = $moneyType;
        $log->sn = $sn;
        $log->changes = $money;
        $log->product_id = $productId;
        $log->mome = $memo;
        if (isset($extend["table_name"])) {
            $log->table_name = $extend["table_name"];
        }
        if (isset($extend["order_num"])) {
            $log->order_num = $extend["order_num"];
        }
        if (isset($extend["tran_time"]) && $extend["tran_time"] > 0) {
            $log->trading_time = $extend["tran_time"];
        }
        $log->save();

        $option = [
            "uid"		=> $mainId, // 收入 或 支出 代理ID
            "typs"		=> $balanceId, // 变更类型 1=分润,2=流量卡,3=达标,4=借款,5=还款,6=赠送,7=提现,8=认购,9=调价，10=采购
            "isChg" 	=> 1, // 1 收入
            "remark" 	=> $memo,	// 备注  => 没有备注传空字符串
            "chgAmt" 	=> $money,	// 变更金额
            "ids" 		=> $productId,	// 操作订单主ID | 分润、达标、流量卡 传入产品ID
            "sn" 		=> $sn,	// SN号
            "times" 	=> isset($extend["tran_time"]) ? $extend["tran_time"] : time(),	// SN号
        ];
        \app\common\controller\Balance::instance()->add_and_logs($option);
    }

    /**
     * 处理订单推送时间超过统计余额时间的订单
     * @param $mainType
     * @param $mainId
     * @param $timeStamp
     * @param $money
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function updateBalance($mainType, $mainId, $timeStamp, $money){
        $date = date("Y-m-d",$timeStamp);
        $balanceTotal = BalanceTotal::where(["main_type" => $mainType,"main_id" => $mainId,"date" => $date])->find();
        if($balanceTotal){
            $balance = Balance::where(["main_type" => $mainType,"main_id" => $mainId])->find();
            $balanceList = BalanceTotal::where(["main_type" => $mainType,"main_id" => $mainId,"date" => [">=",$date]])->order("date asc")->select();
            if($balance && count($balanceList) > 0){
                $balance->money += $money;
                $balance->total += $money;
                $balance->save();

                foreach ($balanceList as $key => $val){
                    $val->income += $money;
                    $val->income_bit += 1;
                    if($key > 0){
                        $val->before += $money;
                    }
                    $val->after += $money;
                    $val->save();
                }

                file_put_contents("updateBalance".date("Ym").".txt","main_type:".$mainType."|main_id:".$mainId."|date:".$timeStamp."|money:".$money.PHP_EOL,FILE_APPEND | LOCK_EX);
            }
        }
    }

    public static function getProductList($mainType, $mainId)
    {
        if ($mainType == 1) {
            $company = Lib::getCompany($mainId);
            $productIds = $company->product_ids;
        } elseif ($mainType == 2) {
            $productIds = [];
        }
        return Product::where("id", "in", $productIds)->field("id,card_type,name")->select();
    }

    //------------------------------------------------------------------
    public static $cardType = [
        1 => "贷记卡",
        2 => "借记卡"
    ];

    public static function getCardTypeCode()
    {
        return [
            "C" => [
                "id" => 1,
                "name" => "贷记卡",
            ],
            "D" => [
                "id" => 2,
                "name" => "借记卡",
            ],
            "05" => [
                "id" => 2,
                "name" => "借记卡",
            ],
            "06" => [
                "id" => 1,
                "name" => "贷记卡",
            ],
            "DC" => [
                "id" => 2,
                "name" => "借记卡",
            ],
            "CC" => [
                "id" => 1,
                "name" => "贷记卡",
            ],
            "SCC" => [
                "id" => 1,
                "name" => "贷记卡",
            ]
        ];
    }

    public static function getCardTypeList(array $ids)
    {
        $list = [];
        foreach ($ids as $key => $val) {
            $list[$val] = self::$cardType[$val];
        }

        return $list;
    }

    public static function getCardTypeObj($ids = "")
    {
        if ($ids == "") {
            $cardTypeList = self::$cardType;
        } else {
            $cardTypeList = [];
            $idsList = explode(",", $ids);
            foreach ($idsList as $k => $v) {
                if (self::$cardType[$v]) {
                    $cardTypeList[$v] = self::$cardType[$v];
                }
            }
        }
        $list = [];
        foreach ($cardTypeList as $key => $val) {
            $list[] = [
                "id" => $key,
                "name" => $val
            ];
        }
        return $list;
    }
    //------------------------------------------------------------------

    public static function isFileExist($pathUrl)
    {
        $path = ROOT_PATH . "/public" . $pathUrl;
        return file_exists($path);
    }

    public static function importExcel($pathUrl)
    {
        $path = ROOT_PATH . "public" . $pathUrl;
        $spreadSheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path);
        $data = $spreadSheet->getActiveSheet()->toArray(null, true, true, false);
        $list = [];
        if(count($data) > 0){
            for ($i = 0;$i<count($data);$i++){
                if($data[$i][0] != null){
                    $list[$i][0] = $data[$i][0];
                }
            }
        }
        return $list;
    }

    public static function getMainInfo($mainType, $mainId)
    {
        switch ($mainType) {
            case 0:
                return ["type" => "超管", "name" => "超管"];
                break;
            case 1:
                $company = Lib::getCompany($mainId);
                return ["type" => "机构", "name" => $company->name];
                break;
            case 2:
                $sale = Lib::getUserInfo($mainId);
                return ["type" => "代理", "name" => $sale->username];
                break;
            default:
                return false;
        }
    }

    public static function getMainInfoApi($mainType, $mainId)
    {
        $code = 0;
        $data = [];
        $msg = "";

        switch ($mainType) {
            case 0:
                $code = 1;
                $data = ["type" => "超管", "name" => "超管"];
                break;
            case 1:
                $company = Lib::getCompany($mainId);
                if ($company) {
                    $code = 1;
                    $data = ["type" => "机构", "name" => $company->name];
                } else {
                    $code = -1;
                    $msg = "机构不存在！";
                }
                break;
            case 2:
                $sale = Lib::getUserInfo($mainId);
                if ($sale) {
                    $code = 1;
                    $data = ["type" => "代理", "name" => $sale->nickname];
                } else {
                    $code = -1;
                    $msg = "代理不存在！";
                }
                break;
            default:
                return false;
        }

        return [
            "code" => $code,
            "data" => $data,
            "msg" => $msg
        ];
    }

    /**
     * @param $mainType
     * @param $mainId
     * @param $productId
     * @param $type || 库存增减类型：1=增加，2=减少
     * @param array $snList || 设备列表
     * @param string $remark || 备注
     * @param int $allocationType  || 调拨类型，1=调拨,2=回退
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function updateStocks($mainType, $mainId, $productId, $type, $snList = [], $remark = "", $allocationType = 0)
    {
        $number = count($snList);
        $stocks = Lib::getStocks($mainType, $mainId, $productId);

        if ($stocks) {
            $before = $stocks->stocks;
            $totalS = $stocks->total_stock;
            $allocation = $stocks->total_allocation;
        } else {
            $before = 0;
            $stocks = new CompanyStocks();
            $stocks->main_type = $mainType;
            $stocks->main_id = $mainId;
            $stocks->product_id = $productId;

            $totalS = 0;
            $allocation = 0;
        }
        $total = $type == 1 ? $before + $number : $before - $number;
        $after = $total;

        if($allocationType > 0){
            if($type == 1){
                $totalStock = $allocationType == 1 ? ($totalS + $number) : $totalS;
                $totalAllocation = $allocationType == 2 ? $allocation - $number : $allocation;
            }else{
                $totalStock = $allocationType == 2 ? $totalS - $number : $totalS;
                $totalAllocation = $allocationType == 1 ? ($allocation + $number) : $allocation;
            }
        }else{
            $totalStock = $totalS;
            $totalAllocation = $allocation;
        }

        $stocks->stocks = $total;
        $stocks->total_stock = $totalStock;
        $stocks->total_allocation = $totalAllocation;
        $stocks->save();

        //记录日志
        $logs = new CompanyStocksLogs();
        $logs->stock_id = $stocks->id;
        $logs->type = $type;
        $logs->before = $before;
        $logs->number = $number;
        $logs->after = $after;
        $logs->remark = $remark;
        $logs->save();
    }
    public static function updateStocks1($mainType, $mainId, $productId, $type, $snList = [], $remark = "", $policyId = 0, $isAllocation = false, $isCallback = false)
    {
        $number = count($snList);
        $stocks = Lib::getStocks($mainType, $mainId, $productId);

        if ($stocks) {
            if ($type == 1) {
                $countNumber = $stocks->stocks + $number;
                if (!$isCallback) {
                    $stocks->total_stock += $countNumber;
                }
            } elseif ($type == 2) {
                if ($stocks->stocks < $number) {
                    return ["code" => -1, "msg" => "库存不足"];
                }
                $countNumber = $stocks->stocks - $number;
                if (!$isCallback) {
                    if ($isAllocation) {
                        $stocks->total_allocation += $number;
                    }
                }
            }

            $before = $stocks->stocks;

            $stocks->stocks = $countNumber;
            $stocks->save(); //更新库存

            $after = $countNumber;
        } else {
            if ($policyId === 0) {
                return ["code" => -1, "msg" => "缺少政策ID"];
            }
            $before = 0;
            $stocks = new CompanyStocks();
            $stocks->main_type = $mainType;
            $stocks->main_id = $mainId;
            $stocks->product_id = $productId;
            $stocks->policy_id = $policyId;
            $stocks->stocks = $number;
            $stocks->total_stock = $number;
            $stocks->save();

            $after = $number;
        }

        //记录日志
        $logs = new CompanyStocksLogs();
        $logs->stock_id = $stocks->id;
        $logs->type = $type;
        $logs->before = $before;
        $logs->number = $number;
        $logs->after = $after;
        $logs->remark = $remark;
        $logs->save();
    }

    /***************************************** 递归获取代理信息 *********************************************/

    // 设置返回代理及机构集合
    public static $topSales = [];

    // 获取当前代理/机构信息
    public static function getUserData($sn)
    {
        self::$topSales = [];
        $fields = "b.id,b.pid,b.ptype,b.nickname as name,2 as utype,d.policy_id";

        $data = Db::name('equip')->alias("a")
            ->join("user b", "b.id = a.main_id", 'LEFT')
            ->join("allocation_details c", 'c.sn = a.sn', 'LEFT')
            ->join("allocation d", 'd.id = c.allocation_id and d.to = a.main_id', 'LEFT')
            ->where(["a.sn" => $sn, "d.confirm_type" => 1, "d.to_type" => 2])
            ->field($fields)
            ->find();
        if (!empty($data)) {
            self::$topSales[] = $data;
            if (isset($data['pid']) && $data['ptype'] == 2) {
                self::getSales($data['pid'], $sn);
            } else {
                self::getCompanyData($data['pid'], $sn);
            }
        }
        return self::$topSales;
    }

    // 递归 获取上级代理信息
    public static function getSales($id, $sn)
    {
        $fields = "b.id,b.pid,b.ptype,b.nickname as name,2 as utype,a.policy_id";
        $data = Db::name('allocation')->alias("a")
            ->join("user b", 'b.id = a.to', 'LEFT')
            ->join("allocation_details c", 'c.allocation_id = a.id', 'LEFT')
            ->where(["c.sn" => $sn, "a.to" => $id, "a.to_type" => 2])
            ->field($fields)
            ->find();
        if (!empty($data)) {
            self::$topSales[] = $data;
            if (isset($data['pid']) && $data['pid'] > 0 && $data['ptype'] == 2) {
                self::getSales($data['pid'], $sn);
            } else {
                self::getCompanyData($data['pid'], $sn);
            }
        }
    }

    // 递归 获取上级机构信息
    public static function getCompanyData($id, $sn)
    {
        $fields = "b.id,b.pid,1 as ptype,b.name,1 as utype,a.policy_id";
        $data = Db::name('allocation')->alias("a")
            ->join("company b", 'b.id = a.to', 'LEFT')
            ->join("allocation_details c", 'c.allocation_id = a.id', 'LEFT')
            ->where(["c.sn" => $sn, "a.to" => $id])
            ->field($fields)
            ->find();
        if (!empty($data)) {
            self::$topSales[] = $data;
            if (isset($data['pid']) && $data['pid'] > 0) {
                self::getCompanyData($data['pid'], $sn);
            }
        } else {
            self::getTopCompanyData($id, $sn);
        }
    }

    // 查询顶级机构信息
    public static function getTopCompanyData($id, $sn)
    {
        $fields = "b.id,b.pid,1 as ptype,b.name,1 as utype,a.policy_id";
        $data = Db::name('company_stocks_confirm')->alias("a")
            ->join("company b", 'b.id = a.company_id', 'LEFT')
            ->join("company_stocks_details c", 'c.confirm_id = a.id', 'LEFT')
            ->where(["c.sn" => $sn, "a.company_id" => $id])
            ->field($fields)
            ->find();
        if (!empty($data)) {
            self::$topSales[] = $data;
        }
    }

    /***************************************** 递归获取代理信息 *********************************************/

    /***************************************** 递归获取团队信息 *********************************************/

    public static function getDirectlyTeamData($id)
    {
        $directly = User::where(['pid' => $id, "ptype" => 2])->field("id,nickname name")->select();
        $data = [];
        foreach ($directly as $val) {
            $team_ids = self::getTeamData($val->id);
            $data[] = [
                'id' => $val->id,
                'name' => $val->name,
                'team_num' => count($team_ids),
                'team_ids' => $team_ids
            ];
        }
        return $data;
    }

    public static function getTeamData($id)
    {
        return self::getTeamIds($id);
    }

    /**
     * 获取代理下面所有团队成员ID
     */
    public static function getTeamIds($id, $includeSelf = true)
    {
        static $ids = [];
        $id = intval($id);  // 将uid 转为 int，默认get方法进来的是 str
        if ($includeSelf) {
            if (!in_array($id, $ids)) {
                array_push($ids, $id);
            }
        }
        $subIds = User::where(['pid' => $id, "ptype" => 2])->field("id")->select();
        $subIds = array_column($subIds, 'id');     // 取出一列； 从$subids中取出id列
        foreach ($subIds as $sub_id) {
            self::getTeamIds($sub_id, $includeSelf);
        }
        $ids = array_unique(array_merge($ids, $subIds)); // 先合并，再去重
        return $ids;
    }

    /***************************************** 递归获取团队信息 *********************************************/

    /***************************************** 提现 - 总余额操作 *********************************************/

    public static function saveBalance($mainType, $mainId, $money, $type = 1)
    {
        $result = false;
        $data = Balance::where(["main_type" => $mainType, "main_id" => $mainId])->find();
        if (!empty($data)) {
            if ($type == 1) {
                // 提现
                if ($data["money"] >= $money) {
                    $result = Balance::where('id', $data["id"])->update(["money" => bcsub($data["money"], $money, 2)]);
                }
            } else {
                // 作废
                $result = Balance::where('id', $data["id"])->update(["money" => bcadd($data["money"], $money, 2)]);
            }
        }
        return $result;
    }

    /***************************************** 提现 - 总余额操作 *********************************************/

    public static function copyUsers($userId){
        //查询是否已经存在复制出来的账号
        $userIds = User::where(["real_id" => $userId])->column("id");
        if(count($userIds) > 0){
            return $userIds;
        }

        $prefixMobile = [
            0 => "136",
            1 => "157",
            2 => "188",
            3 => "199",
        ];
        $user = User::get($userId);

        $params = [];
        for ($i = 0;$i < 4;$i++){
            $mobile = self::getMobile($prefixMobile[$i]);
            $params[] = [
                "company_id" => $user->company_id,
                "pid" => $user->pid,
                "ptype" => $user->ptype,
                "password" => "7bf94136eeea94de3be28b8ea9acc123",
                "salt" => "GyBIwa",
                "withdraw_state" => 2,
                "is_virtual" => 2,
                "real_id" => $userId,
                "username" => $mobile,
                "nickname" => $mobile,
                "mobile" => $mobile,
                "status" => "normal",
                "idcards" => "",
            ];
        }

        $result = false;
        Db::startTrans();
        try {
            $userObj = new User();
            $userObj->saveAll($params);
            $result = true;
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $result = false;
        }

        if($result){
            //查询新复制出来的账号
            $ids = User::where(["real_id" => $userId])->column("id");
            return $ids;
        }else{
            return [];
        }
    }

    public static function getMobile($prefixMobile){
        $mobile = $prefixMobile.Random::numeric(8);
        $user = User::where(["mobile" => $mobile])->find();
        if($user){
            return self::getMobile($prefixMobile);
        }

        return $mobile;
    }
}
